import json

from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse, HttpResponseNotFound, JsonResponse, HttpResponseForbidden
from django.shortcuts import render

# 类视图  ，  原来用到的叫做 函数视图 ， 视图函数
# Create your views here.
from django.views import View


def index(request):
    print(type(request))
    return HttpResponse("视图测试...")


def weather(request, city, date):
    return HttpResponse(f'weather :城市 {city} 日期:{date}')


def qs(request):
    """查询字符串获取"""
    a = request.GET.get("num")
    b = request.GET.get("price")
    b_list = request.GET.getlist("price")
    return HttpResponse(f'参数a：{a}, 参数b：{b} 参数b(列表)：{b_list}')


def regist(request):
    """注册表单
    1.get-->取注册表单，返回表单
    2.post-->获取用户通过表单填写的注册信息,写入到数据库，实现注册
    """
    if request.method == "GET":
        return render(request, 'reqister.html')
    elif request.method == "POST":
        get_a = request.GET.get('a')
        get_uname = request.GET.get('uname')
        print(get_a, get_uname)
        p_dict = request.POST  # 获取post请求参数
        uname = p_dict.get('uname')
        upwd = p_dict.get('upwd')
        ugender = p_dict.get('ugender')
        uhobby = p_dict.getlist('uhobby')  # 爱好是一键多值，使用getlist方法获取所有爱好
        print(f'后台接收到的注册信息：')
        print(f'姓名:{uname} 密码：{upwd} 性别{ugender} 爱好{uhobby}')
        return HttpResponse("注册成功")


def get_body_json(request):
    """取json body数据"""
    json_str = request.body  # {"a": 1, "b": 2}
    json_str = json_str.decode()  # python3.6 无需执行此步
    req_data = json.loads(json_str)  # 把字符串转为 字典类型
    print(req_data, type(req_data))
    print(req_data['gender'])
    print(req_data['age'])
    return HttpResponse('OK')


def get_headers(request):
    """获取请求头数据"""
    # m = request.META

    str = ''
    # 将http请求头拼接返回给浏览器，查看http请求头信息
    # for key, value in m.items():
    for key, value in request.headers.items():
        str += '%s : %s' % (key, value) + '</br>'
    # request其他属性
    print(request.method)
    print(request.user)  # 这个要注释掉， 否则会访问django_session表
    print(request.path)
    print(request.encoding)
    print(request.FILES)
    return HttpResponse(str)


# 【二】 HttpResponse
def resp_view(request):
    # 构建一个HttpResponse
    # resp = HttpResponse(content='你好-Django', content_type='text/html', status=206, charset='GBK')
    resp = HttpResponse()
    # resp.content = '大家好'
    resp.write('好运')
    resp.status_code = 404
    resp.charset = 'GBK'
    # 设置响应头
    resp['major'] = 'Python'
    return resp


def resp_sub(request):
    return HttpResponseForbidden('访问被禁止')


def resp_json(request):
    """返回json数据"""
    content = {'name': "老张", 'gender': "男", "weight": 60}
    # # 把字典转换为json串
    # json_str = json.dumps(content, ensure_ascii=False)
    # resp = HttpResponse(json_str)
    # json_dumps_params={'ensure_ascii': False} :解决中文乱码的问题
    resp = JsonResponse(content, json_dumps_params={'ensure_ascii': False})  #
    return resp


# 【cookie与session】
def get_cookie(request):
    response = HttpResponse('<a href="/viewdemo/send/cookie">客户端默认上传cookie...</a>')
    response.status_code = 200
    # 服务端设置cookie ，传递给客户端
    username = request.GET.get('username')  # 模拟取得用户传递过来的用户名和密码
    password = request.GET.get('password')  # 模拟取得用户传递过来的用户名和密码
    print(username, password)
    response.set_cookie('username', value=username)
    response.set_cookie('password', value=password)
    return response


def send_cookie(request):
    """服务端获取客户端传递过来的cookie"""
    for item in request.COOKIES.items():
        print(item)
    return HttpResponse("ok!")


def set_session(request):
    """视图函数 ，测试session"""
    # 比如说 用户信息  name ，age ，gender
    name = request.GET.get('name')
    pwd = request.GET.get('password')
    # age = request.GET.get('age')
    # gender = request.GET.get('gender')
    request.session['name'] = name  # 以键值对的方 式设置session
    request.session['password'] = pwd
    # request.session['gender'] = gender
    return HttpResponse("设置session成功")


def get_session(request):
    name = request.session.get('name')
    pwd = request.session.get('password')
    print(name)
    print(pwd)
    return HttpResponse("获取到session的值")


"""类视图
对数据库中的数据访问： 
 1. 增加 一条记录 post 
 2. 删除 一条记录 delete
 3. 修改 一条记录 put
 4. 查询 一条记录 get
"""


class Regist(View):
    def get(self, request):
        return HttpResponse("类视图 ，get查询，取得数据请求")

    def post(self, request):
        return HttpResponse("类视图 ，Post增加请求")

    def put(self, request):
        return HttpResponse("类视图 ，put修改请求")

    def delete(self, request):
        # 模拟删除
        return HttpResponse("类视图 ，delete删除请求")
